/*
 * @filename EncryptUtils.java
 * @author barry
 * @version 0.0.1
 * @date 2019年12月18日
 */
package com.bnzj.core.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;

/**
 * @author barry
 * @date 2019-12-18
 */
public class EncryptUtils {

    /**
     * 生成RSA密钥对
     * @return
     */
    static KeyPair generateKeyPair() {
        try {
            return KeyPairGenerator.getInstance("RSA").generateKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 读取RSA密钥对
     * @param is
     * @param password
     * @return
     * @throws Exception
     */
    static KeyPair readKeyPair(InputStream is, char[] password) throws Exception {
        PEMParser pemParser = new PEMParser(new InputStreamReader(is));
        Object object = pemParser.readObject();
        pemParser.close();
        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();//.setProvider("BC");
        // 获得密钥对
        KeyPair kp = null;
        if (object instanceof PEMEncryptedKeyPair) {
            kp = converter.getKeyPair(((PEMEncryptedKeyPair)object).decryptKeyPair(decProv));
        } else {
            kp = converter.getKeyPair((PEMKeyPair)object);
        }
        return kp;
    }
}
